import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';

/**
 * 日期格式化
 */
class DateTimeDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DateTimeStateDemo();
  }
}

class DateTimeStateDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return DateTimeState();
  }
}

class DateTimeState extends State<DateTimeStateDemo> {
  DateTime _selectedDate = DateTime.now();

  TimeOfDay _timeOfDate = TimeOfDay(
    hour: 9,
    minute: 30,
  );

  /**
   *日期弹出框
   */
  Future<void> _selectDate() async {
    DateTime dateTime = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
    );
    if (dateTime == null) return null;
    setState(() {
      _selectedDate = dateTime;
    });
  }

  /**
   * 时间选择器
   * async 异步方法
   * await 等待异步返回的结果
   */
  Future<void> _selectTime() async {
    final TimeOfDay time = await showTimePicker(
      context: context,
      initialTime: _timeOfDate,
    );

    if (time == null) {
      return null;
    }

    setState(() {
      _timeOfDate = time;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DateTimeDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                InkWell(
                  onTap: () {
                    _selectDate();
                  },
                  child: Row(
                    children: <Widget>[
                      Text(
                        DateFormat.yMMMd().format(_selectedDate),
                      ),
                      Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {
                    _selectTime();
                  },
                  child: Row(
                    children: <Widget>[
                      Text(
                        _timeOfDate.format(context),
                      ),
                      Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
